<template>
  <div v-if="!paramsError" class="app-container detail-container">
    <div class="detail-title">
      {{ textMap[type] }}
    </div>
    <el-form ref="form" :rules="rules" :model="form" :label-width="labelWidth" class="detail-form">
      <el-row :gutter="100">
        <el-col :span="10">
          <el-form-item :label="lang.systemManage.user.index.tableCol.username" prop="username">
            <el-input
              v-model.trim="form.username"
              :disabled="type === 'detail'"
              :placeholder="`请输入${lang.systemManage.user.index.tableCol.username}(${lang.systemManage.user.index.tableCol.phone})`"
              maxlength="11"/>
          </el-form-item>
          <el-form-item :label="lang.systemManage.user.index.tableCol.type" prop="type">
            <el-radio-group v-model="form.type" :disabled="type === 'detail' && (form.type === -1 || form.type === 4)">
              <el-radio
                v-for="item in userType(form.type)"
                :key="item.value"
                :label="item.value"
                :disabled="form.type === 4">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="lang.systemManage.user.index.tableCol.realname" prop="realname">
            <el-input v-model.trim="form.realname" :placeholder="`请输入${lang.systemManage.user.index.tableCol.realname}`" maxlength="20" />
          </el-form-item>
          <!-- <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio
                v-for="item in $store.getters.sexs"
                :key="item.value"
                :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item :label="lang.systemManage.user.index.tableCol.email" prop="email">
            <el-input v-model="form.email" :placeholder="`请输入${lang.systemManage.user.index.tableCol.email}`" maxlength="180" />
          </el-form-item>
          <el-form-item :label="lang.systemManage.user.index.tableCol.phone" prop="phone">
            <el-input
              v-model.trim="form.phone"
              :placeholder="`请输入${lang.systemManage.user.index.tableCol.phone}`"
              type="p"
              maxlength="11"/>
          </el-form-item>
          <el-form-item v-if="type === 'create'" :label="lang.systemManage.user.index.tableCol.password">
            <el-tooltip
              :content="`默认${lang.systemManage.user.index.tableCol.password}为：123456`"
              effect="light"
              placement="top-start">
              <el-input v-model.trim="form.password" type="password" disabled />
            </el-tooltip>
          </el-form-item>
          <el-form-item :label="lang.systemManage.user.index.tableCol.enable">
            <el-switch v-model="form.enable" :active-value="1" :inactive-value="0" />
            <span :class="form.enable ? 'active': ''" class="switch-text">（{{ form.enable ? '开启' : '关闭' }}）</span>
          </el-form-item>
          <el-form-item :label="lang.systemManage.user.index.tableCol.remark">
            <el-input
              v-model="form.remark"
              :autosize="{minRows: 5, maxRows: 10}"
              :placeholder="`请输入${lang.systemManage.user.index.tableCol.remark}`"
              type="textarea"
              maxlength="240"/>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="9">
          <div class="img-select-container">
            <div class="img-select">
              <img :src="form.base64 || (this.$store.getters.ossUrl + form.headImg) || defaultHeadImg" :onerror="`this.src='${defaultHeadImg}'`" >
            </div>
            <el-button type="default" @click="selectHeadImgInput.click()">选择头像</el-button>
          </div>
        </el-col> -->
      </el-row>
    </el-form>
    <div :style="{'padding-left': labelWidth}" class="detail-buttons">
      <el-button v-waves v-if="type === 'create'" :loading="saveLoading" type="primary" @click="save()">
        {{ lang.systemManage.user.detail.operationBtn.create }}
      </el-button>
      <el-button v-waves v-else :loading="saveLoading" type="primary" @click="edit()">
        {{ lang.systemManage.user.detail.operationBtn.update }}
      </el-button>
      <el-button v-waves type="default" @click="$$closeTag()">
        {{ lang.systemManage.user.detail.operationBtn.close }}
      </el-button>
    </div>
    <!-- <detail-cropper v-if="headImg !== null" ref="cropper" :img="headImg" @img-cropper="imgCropper" /> -->
  </div>
</template>

<script>
import CloseTagMixin from '@/mixins/closeTag'
import { getUserById, userAdd, userUpdate } from '@/api/systemManage/user'
// import SparkMD5 from 'spark-md5'
import waves from '@/directive/waves' // Waves directive
import defaultHeadImg from '@/assets/defaultHeadImg.png'
// import DetailCropper from './detail_cropper'
// import { isvalidPhone } from '@/utils/validate'
import { mapGetters } from 'vuex'

export default {
  name: 'UserManageItem',
  directives: { waves },
  components: {
    // DetailCropper
  },
  mixins: [CloseTagMixin],
  data() {
    const langIndex = this.$store.getters.lang.systemManage.user.index
    const langDetail = this.$store.getters.lang.systemManage.user.detail
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(`${langIndex.tableCol.phone}不能为空`))
      } else {
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error(`请输入正确的${langIndex.tableCol.phone}`))
        }
      }
    }
    return {
      textMap: {
        create: langDetail.titleTag.create2,
        detail: langDetail.titleTag.detail
      },
      labelWidth: '100px',
      id: this.$route.params.id,
      type: this.$route.params.type,
      saveLoading: false,
      paramsError: false,
      selectHeadImgInput: null,
      headImg: null,
      form: {
      },
      defaultPassword: this.$store.getters.defaultPassword,
      rules: {
        username: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        type: [
          { required: true, message: `请选择${langIndex.tableCol.type}`, trigger: 'change' }
        ],
        realname: [
          { required: true, message: `请输入${langIndex.tableCol.realname}`, trigger: 'blur' }
        ],
        // nickName: [
        //   { required: true, message: '请输入昵称', trigger: 'blur' }
        // ],
        // sex: [
        //   { required: true, message: '请选择性别', trigger: 'change' }
        // ],
        email: [
          { required: true, message: `请输入${langIndex.tableCol.email}`, trigger: 'blur' },
          { type: 'email', message: `请输入正确的${langIndex.tableCol.email}`, trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: `请输入${langIndex.tableCol.phone}`, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'lang'
    ]),
    userType() {
      return function(_userType) {
        const userType = this.$store.getters.userType
        const _keys = Object.keys(userType)
        const newUserType = []
        for (let i = 0; i < _keys.length; i++) {
          if (this.type === 'create' && _keys[i] === '4') continue
          if (this.type === 'detail' && _keys[i] === '4' && _userType !== 4) continue
          if (_keys[i] === '-1' && _userType !== -1) continue
          if (_keys[i] === '3' && _userType !== 3) continue
          newUserType.push({
            label: userType[_keys[i]].name,
            value: parseFloat(_keys[i])
          })
        }
        return newUserType
      }
    },
    validatePassword() {
      return this.form.password === this.defaultPassword
    },
    defaultHeadImg() { return defaultHeadImg }
  },
  created() {
    // this.getPasswordMd5()
    // 参数type验证
    switch (this.type) {
      case 'create':
        // 设置标签名称
        this.$store.dispatch('setTagName', {
          path: this.$route.path,
          title: this.lang.systemManage.user.detail.titleTag.create
        })
        break
      case 'detail': this.getInfo(); break
      default: {
        this.paramsError = true
        this.$message.info('页面参数不正确，请重新打开页面！')
        return
      }
    }
    // 初始化数据模板
    this.formReset()
    // 创建input元素，做选择文件
    this.selectHeadImgInput = document.createElement('input')
    this.selectHeadImgInput.setAttribute('type', 'file')
    this.selectHeadImgInput.setAttribute('accept', 'image/*')
    this.selectHeadImgInput.onchange = (event) => {
      this.selectHeadImg(event)
    }
  },
  methods: {
    formReset() {
      this.form = {
        username: '',
        type: '',
        nickName: '',
        sex: '',
        email: '',
        phone: '',
        password: this.defaultPassword,
        enable: 1,
        remark: '',
        realname: ''
      }
      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
    },
    getInfo() {
      getUserById(this.id).then(res => {
        console.log(res)
        const data = res.data
        this.form = data
        // 设置标签名称
        this.$store.dispatch('setTagName', {
          path: this.$route.path,
          title: `${data.nickName || data.username}-${this.lang.systemManage.user.detail.titleTag.detail}`
        })
      }).catch(e => {
        this.$message.error(this.$store.getters.errorMsg)
      })
    },
    selectHeadImg(event) {
      if (event.target && event.target.files) {
        this.headImg = event.target.files[0]
        this.$nextTick(() => {
          this.$refs.cropper.toggle(true)
        })
      }
    },
    imgCropper(data) {
      this.form.base64 = data
      this.$forceUpdate()
    },
    save() {
      if (!this.validatePassword) {
        this.formReset()
        this.$message.warning('请不要私自修改初始密码！')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          userAdd(this.form).then(res => {
            this.saveLoading = false
            this.$message.success('创建成功！')
            this.formReset()
          }).catch(e => {
            this.saveLoading = false
            this.$message.error(e)
          })
        } else return false
      })
    },
    edit() {
      delete this.form.password
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          userUpdate(this.form).then(res => {
            this.saveLoading = false
            this.$message.success('更新成功！')
          }).catch(e => {
            this.saveLoading = false
            this.$message.error(e)
          })
        } else return false
      })
    }
    // getPasswordMd5() {
    //   const spark = new SparkMD5()
    //   spark.append(this.defaultPassword)
    //   this.form.password = spark.end()
    //   console.log(this.form.password)
    // }
  }
}
</script>

<style lang="scss">
.detail-container{
}
</style>
<style lang="scss" scoped>
.switch-text{
  color: #bbb;
  margin-left: 10px;
  font-size: 12px;
  &.active{
    color: #409EFF;
  }
}
.img-select-container{
  width: 180px;
  text-align: center;
  .img-select{
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
    position: relative;
    img{
      width: 100%;
      height: 100%;
    }
    .el-button{
      display: inline-block;
      margin-top: 20px;
    }
  }
}
</style>

